package com.orangelife.mobile.web;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.jump.HouseJumper;
import com.common.sp.UserSp;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.app.service.MyService;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.constants.CommonURL;
import com.orangelife.mobile.constants.WebViewURL;
import com.orangelife.mobile.main.biz.JumpUtil;
import com.orangelife.mobile.util.LogE;
import com.orangelife.mobile.util.UriUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import org.json.JSONObject;

/**
 * 目前操作分为两种：1、Javascript函数回调的方法（方法写在CommonJS及其子类中，比如jump、share、title、id等） ； 2、通用处理；WebActivity只有标题栏和WebView两个部分，写在本Activity中；
 * Created by Administrator on 2015/11/24.Modify by wgf on 160824.
 */
public class WebActivity extends OrangeLifeBaseActivity {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.adshow_menubar)
    View topBar;
    @Bind(R.id.wvDesc)
    WebWin wvDesc;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    @Bind(R.id.iv_title_right)
    ImageView ivRight;
    @Bind(R.id.llRightClick)
    LinearLayout llRightClick;
    @Bind(R.id.tvTitle2)
    TextView tvTitle2;
    @Bind(R.id.llBack2)
    LinearLayout llBack2;
    @Bind(R.id.ivBack2)
    ImageView ivBack2;
    public String path;
    @Bind(R.id.titleTransparent)
    View topBar2;

    private CommonJs jsUtil;
    WebHandler mHandler;

    private String mFunctionJson;

    public MyService.MyBinder myBinder;
    private boolean isBound;
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MyService.MyBinder) service;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ad_show);
        ButterKnife.bind(this);
        serviceBind();
        initWebSetting();
        setListener();
        init();
    }

    private void init() {
        getIntentInfo();//更新PATH
        initTitle();//更新标题
        initUtil();//处理path，增加JS
         /*每个不同的界面，有不同的javascript函数，以及不同的界面处理，只有标题栏*/
        wvDesc.addJavascriptInterface(jsUtil, JsUtil.JS_INTERFACE_NAME);
        wvDesc.loadUrl(path);
    }

    @Override
    protected void onPause() {
        /*解决关闭网页之后，网页上音频没有被关闭的错误*/
//        wvDesc.reload();
        super.onPause();
        LogE.E("onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogE.E("onStop");
    }

    @Override
    protected void onDestroy() {
        if (isBound) {
            unbindService(connection);
        }
        wvDesc.reload();
        super.onDestroy();
        LogE.E("onDestroy");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //该Activity是singleTask模式，在已生成Activity后，再次跳入，若不重新设置intent，则intent数据不会更新；
        setIntent(intent);
        Bundle bundle = intent.getExtras();
        if (!StringUtil.isBlank(path) && bundle != null) {
            if (bundle.getBoolean("isBackForJs")) {//认证跳回来的
                switch (bundle.getInt("id")) {
                    case 0:
                        invokeJavaScriptFunction((HashMap<String, Object>) bundle.getSerializable("map"));
                        break;
                    default:
                        LogE.E(WebActivity.class.getSimpleName(), "javascript back id is null!");
                        break;
                }
            } else {//其他地方跳进来
                if (wvDesc != null) {
                    wvDesc.clearView();
                }
                if (tvTitle2 != null && tvTitle != null) {
                    tvTitle.setText("");
                    tvTitle2.setText("");
                }
                init();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void getIntentInfo() {//更新path
        Intent data = getIntent();
        path = data.getStringExtra("uri");
        path = UriUtil.replaceUri(this, path);
    }

    private void initUtil() {
        path = PathUtil.handlePath(path);
        mHandler = new WebHandler(this);
        TitleBarUtil.handleTitleBar(path, mHandler);
        jsUtil = JsUtil.getJSI(path, this, mHandler);
    }

    private void initTitle() {
        tvTitle.setText(UriUtil.getValue(path, "title"));
    }

    private void initWebSetting() {
        WebSettings webSettings = wvDesc.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDomStorageEnabled(true);

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSettings.setUseWideViewPort(true);
        
        wvDesc.setWebViewClient(new MyWebViewClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {/*Webview在安卓5.0之前默认允许其加载混合网络协议内容,在安卓5.0之后，默认不允许加载http与https混合内容，需要设置webview允许其加载混合网络协议内容*/
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        /*使alert能弹出来*/
        wvDesc.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                /*URL没有传标题,且页面的title标签有标题*/
                if (tvTitle != null
                        && tvTitle2 != null
                        && tvTitle.getText().length() == 0
                        && tvTitle2.getText().length() == 0
                        && StringUtil.isBlank(UriUtil.getValue(path, "title"))
                        && !StringUtil.isBlank(title)
                        && !removeHttpPrefix(title).equals(removeHttpPrefix(wvDesc.getUrl()))    /*在Android6.0系统里面，onReceivedTitle方法默认会调用两边，第一遍title现实的是当前webview的url，第二遍才是从连接中获取的tiitle，因此为了避免刷新webview的时候，会在title的位置显示url，可以做如下处理*/
                        ) {/*尚未设置标题,且URL不带标题,且HTML有标题*/
                    handleTitleBar(WebWhat.SET_HTML_TITLE, title);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
    }

    private String removeHttpPrefix(String url) {
        return url == null ? "" : url.replace("http://", "").replace("https://", "");
    }

    private void setListener() {
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtil.isBlank(path)) {
                    wvDesc.loadUrl(path);
                }
            }
        });
    }


    public void handleTitleBar(int mode, String title) {
        switch (mode) {
            case WebWhat.SET_HTML_TITLE:
                if (!StringUtil.isBlank(title)) {
                    tvTitle.setText(title);
                }
                if (!StringUtil.isBlank(title)) {
                    tvTitle2.setText(title);
                }
                break;
            case WebWhat.HIDE_TILTE:
                hideTitleBar1();
                hideTitleBar2();
                break;
            case WebWhat.SHOW_RIGHT_ICON:
                showRightIcon(R.drawable.my_comm_act_gold, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String path = CurryApplication.getInstance().getServerURL() + WebViewURL.COMMUNITY_ACTIVITY_ORDER_LIST + "?accessToken=" + UserSp.getAccessToken();
                        wvDesc.loadUrl(path);
                        dataTrackClick("btnmyCA", null);
                    }
                });
                break;
            case WebWhat.HIDE_RIGHT_ICON:

                hideRightIcon();
                break;
            case WebWhat.SHOW_TITLE2:
                showTopBar2();
                hideTitleBar1();
                if (!StringUtil.isBlank(title)) {
                    tvTitle2.setText(title);
                }
                break;
            case WebWhat.SHOW_TITLE1:
                showTopBar1();
                hideTitleBar2();
                if (!StringUtil.isBlank(title)) {
                    tvTitle.setText(title);
                }
                break;
        }
    }

    /** 显示右边 */
    private void showRightIcon(int drawableID, View.OnClickListener listener) {
        ivRight.setVisibility(View.VISIBLE);
        ivRight.setBackgroundResource(drawableID);
        if (listener != null) {
            llRightClick.setOnClickListener(listener);
        }
    }

    private void hideRightIcon() {
        ivRight.setVisibility(View.GONE);
    }

    /** 隐藏标题栏 */
    private void hideTitleBar1() {
        topBar.setVisibility(View.GONE);
    }

    private void hideTitleBar2() {
        topBar2.setVisibility(View.GONE);
    }

    private void showTopBar1() {
        wvDesc.setVisibility(View.GONE);
        topBar.setVisibility(View.VISIBLE);
        wvDesc.setVisibility(View.VISIBLE);
    }

    private void serviceBind() {
        Intent intent = new Intent(this, MyService.class);
        isBound = bindService(intent, connection, BIND_AUTO_CREATE);
    }

    /**
     * 请求版本更新
     */
    public void requestUpdateVersion(final Activity context) {
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("appType", "1");
        VolleyHttpUtil.getInstance().getWithCallback(CommonURL.VERSION, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                boolean isSuccess = false;
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject, false)) {
                    isSuccess = true;
                    Map<String, Object> map = OrangeDataHandler.getMapWithEntityNoGson(jsonObject);
                    if (map != null && map.size() > 0) {

                        final String url = String.valueOf(map.get("url"));
                        myBinder.setAppURL(url);
                        myBinder.setContext(WebActivity.this);
                        myBinder.functionUpdate();
                    }
                }
                if (!isSuccess) {
                    com.curry.android.util.ToastHelper.getInstance()._toast("获取版本信息失败");
                }
            }
        });
    }

    private void showTopBar2() {
        topBar2.setVisibility(View.VISIBLE);
        topBar2.getBackground().setAlpha(0);
//        wvDesc.setOnOrangeWebViewScrollListener(new OnOrangeWebViewScrollListener() {
//
//            @Override
//            public void onScrollChanged(int l, int scrollY, int oldl, int oldt) {

//                int alphaNow = 0;
//                if (scrollY == 0) {
//                    alphaNow = 0;/*透明*/
//                } else if (scrollY > 350) {
//                    alphaNow = 255;/*白色*/
//                } else {
//                    alphaNow = (alphaNow * (scrollY / 350));
//                }
//                topBar2.getBackground().setAlpha(alphaNow);
//                if (alphaNow > 200) {
//                    ivBack2.setBackgroundResource(R.drawable.ic_shadow_back);
////                    topBar2.setBackgroundColor(getResources().getColor(R.color.white));
//                } else {
//                    ivBack2.setBackgroundResource(R.drawable.ic_shadow_back);
//                }
//            }
//        });
    }


    /** XML中属性onClick用 */
    public void onBackClick(View v) {
        goToBack(v);
    }

    @Override
    public void onBackPressed() {
        if (wvDesc.canGoBack()) {
            DataTrack.clickTrack("btnBack", null);
            wvDesc.goBack();
        } else {
            super.onBackPressed();
        }
    }

    private void goToBack(View v) {
        if (wvDesc.canGoBack()) {
            wvDesc.goBack();
            DataTrack.clickTrack("btnBack", null);
        } else {
            DataTrack.clickTrack("closeH5", null);
            finish();
            /*增加动画*/
            IntentHelper.getInstances().jumpActivityAnimation(this, true);
        }
    }

    public void jump(String path) {
        finish();
        JumpUtil.jumpActivityWithoutHost(this, path);
    }

    public void jumpCert() {
//        JumpUtil.jumpActivity(this, );
        HouseJumper.jumpToCertFromWeb(this);
    }

    public void setFunctionJson(String functionJson) {
        this.mFunctionJson = functionJson;
    }

    //{"callBackFn":"authentication","params":{},"code","0"}
    public void invokeJavaScriptFunction(HashMap<String, Object> appendMap) {
        if (StringUtil.isBlank(mFunctionJson)) {
            return;
        }
        Map<String, Object> map = JSONHelper.jsonToMap(mFunctionJson);
        if (map == null) {
            return;
        }
        if (appendMap != null) {
            for (Map.Entry<String, Object> entry : appendMap.entrySet()) {
                map.put(entry.getKey(), entry.getValue());
            }
        }
        String functionName = String.valueOf(map.get("callBackFn"));
        String jsonParam = String.valueOf(JSONHelper.Map2Json(map));
        String js = "javascript:" + functionName + "('" + jsonParam + "',)";
        LogE.E(js);
        wvDesc.loadUrl(js);
    }

    public void invokeJavaScriptFunction2(String json) {
        wvDesc.loadUrl(json);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            ToastHelper.getInstance()._toast(String.valueOf(data.getStringExtra("isCert")));
        }
    }

    class MyWebViewClient extends WebViewClient {

        public MyWebViewClient() {
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            /*注意：super句话一定要删除，或者注释掉，否则又走handler.cancel(),WebView默认的不支持https的了。*/
            /*super.onReceivedSslError(view, handler, error);*/
            /*handler.cancel(); *//* Android默认的处理方式*/
            /*handler.handleMessage(Message msg); *//* 进行其他处理*/
            handler.proceed(); /* 接受所有网站的证书*/
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                startActivity(intent);
                return true;
            } else {
                LogE.E(WebActivity.class.getSimpleName(), "重定向後的URL=" + url);
                showDialog();
                return super.shouldOverrideUrlLoading(view, url);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            emptyLayout.dismiss();
            emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }

        /**
         * 要等js全部加载完毕后，才能过调用js函数
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (emptyLayout != null) {
                emptyLayout.dismiss();
            }
            closeDialog();
//            webView.loadUrl("javascript:setInviteCode(" + code + ")");
        }
    }
}